<template>
  <div class="course-image">
    <el-progress
      v-if="isUploading"
      type="circle"
      :percentage="percentage"
      width="178"
      :status="percentage === 100 ? 'success' : undefined"
    ></el-progress>
    <el-upload
      v-else
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="handleUpload"
    >
      <img v-if="img" :src="img" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { uploadCourseImage } from '/@/services/Course'
export default defineComponent({
  name: 'CourseImage',
  components: {},
  props: {
    img: {
      type: String,
      default: ''
    },
    limit: {
      type: Number,
      default: 2
    }
  },
  setup(props: any, context: any) {
    const beforeAvatarUpload = ref((file: any) => {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < props.limit

      if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    })
    const handleUpload = ref(async (options: any) => {
      isUploading.value = true
      const fd = new FormData()
      fd.append('file', options.file)
      const { data } = await uploadCourseImage(fd, (e: any) => {
        percentage.value = Math.floor((e.loaded / e.total) * 100)
      })
      context.emit('update:img', data.data.name)
      isUploading.value = false
      percentage.value = 0
    })
    const isUploading = ref(false)
    const percentage = ref(0)
    return {
      handleUpload,
      beforeAvatarUpload,
      isUploading,
      percentage
    }
  },
  created() {}
})
</script>
<style lang="scss" scoped>
::v-deep .avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}

::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  width: 178px;
  height: 178px;
  font-size: 28px;
  line-height: 178px;
  color: #8c939d;
  text-align: center;
}

.avatar {
  display: block;
  width: 178px;
  height: 178px;
}
</style>
